import sys
from PyQt5.QtWidgets import QMainWindow, QApplication,QTableWidgetItem,QPushButton,QWidget#,QHeaderView,QPushButton,,QAbstractItemView
from PyQt5.QtCore import Qt,QObject,pyqtSignal,QEvent#,QStringListModel,QTextStream,pyqtSignal,QSize
from PyQt5.QtGui import QIcon,QFont,QColor

from articlGUI_ui import Ui_MainWindow
from common import groupToProduct
from tinydb import TinyDB, Query,where
db = TinyDB('tinydb.json')
articleCol= db.table('articles')
class MyWin(QMainWindow,Ui_MainWindow):
    def __init__(self,groupToProduct) -> None:
        super().__init__()
        self.setupUi(self)
        self.groupToProduct=groupToProduct

        self.comboBox.addItems([productName for productName in self.groupToProduct])
        # self.label.setText('<a href="https://www.baidu.com/">hello,点我跳转')
        # self.label.setStyleSheet('color: blue')
        # self.label.setOpenExternalLinks(True)  # Prevent from opening links externally
        # self.label.setTextInteractionFlags(Qt.TextSelectableByMouse|Qt.LinksAccessibleByMouse)
        
        self.comboBox.currentTextChanged.connect(self.on_categoryChanged)
        self.comboBox_2.currentTextChanged.connect(self.on_productChanged)
    def on_categoryChanged(self,newtext):
        print(newtext)
        self.comboBox_2.clear()
        self.comboBox_2.addItems([productName for productName in self.groupToProduct[newtext]])
    def on_productChanged(self,productName):
        print(productName)
        if len(productName.strip())==0:return
        ls=articleCol.search(where('product_name')==productName)
        ls=sorted(ls, key=lambda x: x['publicTime'],reverse= True)
        self.textBrowser.clear()
        for item in ls:
            print(item['title'],item['url']) 
            link='<a href="%s">%s-%s-%s</a>'%(item['url'],item['publicTime'].split(' ')[0],item['articleFrom'],item['title'])
            self.textBrowser.append(link)
        self.statusbar.showMessage("%s %d条"%(productName,len(ls)),10000)
if __name__=="__main__":
    app = QApplication(sys.argv)
    myGui=MyWin(groupToProduct)
    myGui.show()
    sys.exit(app.exec())